<template>
  <div class="role-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加角色
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="角色名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入角色名称"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 角色表格 -->
      <el-table
        :data="roleList"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色代码" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="权限数量">
          <template #default="{ row }">
            <el-tag type="info">{{ row.permissions?.length || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '激活' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" />
        <el-table-column label="操作" width="250">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="showEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="showPermissionDialog(row)"
            >
              权限配置
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="deleteRole(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="roleForm"
        :rules="formRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色代码" prop="code">
          <el-input v-model="roleForm.code" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="roleForm.is_active" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限配置"
      width="800px"
    >
      <div class="permission-config">
        <div class="current-role">
          <strong>当前角色：{{ currentRole?.name }}</strong>
        </div>
        
        <el-tree
          ref="permissionTreeRef"
          :data="permissionTreeData"
          :props="{ children: 'children', label: 'name' }"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectedPermissions"
          @check="handlePermissionCheck"
        />
      </div>
      
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePermissions" :loading="permissionLoading">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import api from '@/utils/api'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const permissionLoading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const dialogTitle = ref('添加角色')
const isEdit = ref(false)
const editRoleId = ref(0)

const roleList = ref([])
const permissionList = ref([])
const permissionTreeData = ref([])
const selectedPermissions = ref([])
const currentRole = ref(null)

const formRef = ref<FormInstance>()
const permissionTreeRef = ref()

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 角色表单
const roleForm = reactive({
  name: '',
  code: '',
  description: '',
  is_active: true
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色代码', trigger: 'blur' }
  ]
}

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  try {
    const response = await api.get('/rbac/roles/', {
      params: {
        page: pagination.page,
        page_size: pagination.pageSize,
        ...searchForm
      }
    })
    
    if (response.data.success) {
      roleList.value = response.data.data.results
      pagination.total = response.data.data.total
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取权限列表
const fetchPermissionList = async () => {
  try {
    const response = await api.get('/rbac/permissions/')
    if (response.data.success) {
      permissionList.value = response.data.data.results
      // 构建权限树结构（这里简化处理，实际可能需要更复杂的树结构）
      permissionTreeData.value = response.data.data.results
    }
  } catch (error) {
    console.error('获取权限列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchRoleList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, { name: '' })
  pagination.page = 1
  fetchRoleList()
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchRoleList()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchRoleList()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加角色'
  isEdit.value = false
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (role: any) => {
  dialogTitle.value = '编辑角色'
  isEdit.value = true
  editRoleId.value = role.id
  
  Object.assign(roleForm, {
    name: role.name,
    code: role.code,
    description: role.description || '',
    is_active: role.is_active
  })
  
  dialogVisible.value = true
}

// 显示权限配置对话框
const showPermissionDialog = (role: any) => {
  currentRole.value = role
  selectedPermissions.value = role.permissions?.map((p: any) => p.id) || []
  permissionDialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(roleForm, {
    name: '',
    code: '',
    description: '',
    is_active: true
  })
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        let response
        if (isEdit.value) {
          response = await api.put(`/rbac/roles/${editRoleId.value}/`, roleForm)
        } else {
          response = await api.post('/rbac/roles/', roleForm)
        }
        
        if (response.data.success) {
          ElMessage.success(`角色${isEdit.value ? '更新' : '创建'}成功`)
          dialogVisible.value = false
          fetchRoleList()
        }
      } catch (error) {
        console.error('操作失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除角色
const deleteRole = async (role: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 ${role.name} 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await api.delete(`/rbac/roles/${role.id}/`)
    if (response.data.success) {
      ElMessage.success('角色删除成功')
      fetchRoleList()
    }
  } catch (error) {
    // 用户取消操作
  }
}

// 权限选择变化
const handlePermissionCheck = (data: any, checked: any) => {
  // 处理权限选择逻辑
}

// 保存权限配置
const savePermissions = async () => {
  if (!currentRole.value) return
  
  permissionLoading.value = true
  try {
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const response = await api.put(`/rbac/roles/${currentRole.value.id}/`, {
      permission_ids: checkedKeys
    })
    
    if (response.data.success) {
      ElMessage.success('权限配置保存成功')
      permissionDialogVisible.value = false
      fetchRoleList()
    }
  } catch (error) {
    console.error('保存权限配置失败:', error)
  } finally {
    permissionLoading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchRoleList()
  fetchPermissionList()
})
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.permission-config {
  padding: 20px 0;
}

.current-role {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>
